package com.pricl.frame.query.page;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;

import com.github.miemiedev.mybatis.paginator.domain.PageBounds;

public class PageFactory {

	public static Logger LOGGER = LoggerFactory.getLogger(PageFactory.class);
	public static final int MAX_PAGE_LIMIT = 1000;
	public static final int DEFAULT_PAGE_LIMIT = 10;
	public static final String PARAME_PAGE_NUMBER = "pageNo";
	public static final String PARAME_PAGE_LIMIT = "pageLimit";
	public static final String PARAME_PAGE_SORT = "sortType";
	public static final String PARAME_PAGE_SORT_FIELD = "sortField";

	public static PageBounds builderPageBounds(HttpServletRequest request) {
		int pageNumber = 1;
		try {
			pageNumber = Integer.valueOf(request.getParameter("pageNo")).intValue();
		} catch (Exception ex) {
			pageNumber = 1;
			LOGGER.warn("builder PageBounds Object Request param:pageNo:" + request.getParameter("pageNo")
					+ "Can not converter Integer Type.default " + "pageNo" + ":1");
		}
		int pageLimit = 10;
		try {
			pageLimit = Integer.valueOf(request.getParameter("pageLimit")).intValue();
		} catch (Exception ex) {
			pageLimit = 10;
			LOGGER.warn("builder PageBounds Object Request param:pageLimit:" + request.getParameter("pageLimit")
					+ "Can not converter Integer Type.default " + "pageLimit" + ":" + 10);
		}

		if (1000 < pageLimit) {
			pageLimit = 1000;
		}
		return new PageBounds(pageNumber, pageLimit);
	}

	public static PageRequest buildPageRequest(HttpServletRequest request) {
		String sortType = request.getParameter("sortType");

		String sortField = request.getParameter("sortField");

		Sort sort = null;
		if (!StringUtils.isEmpty(sortField)) {
			if ("desc".equals(sortType))
				sort = new Sort(Sort.Direction.DESC, new String[] { sortField });
			else {
				sort = new Sort(Sort.Direction.ASC, new String[] { sortField });
			}
		}
		PageBounds pageBounds = builderPageBounds(request);
		return new PageRequest(pageBounds.getPage() - 1, pageBounds.getLimit(), sort);
	}
}
